#include "rtsp_h264liveSMS.h"


rtsp_h264liveSMS::rtsp_h264liveSMS(UsageEnvironment & env,
                                   FramedSource * source,
                                   CRingBuffer<VidPacket> *ringbuffer)
								   :OnDemandServerMediaSubsession(env, True)
{
    m_ringBuffer = ringbuffer;
	m_pSource = source;
	m_pSDPLine = 0;
}

rtsp_h264liveSMS::~rtsp_h264liveSMS(void)
{
	if (m_pSDPLine)
	{
		free(m_pSDPLine);
	}
}

rtsp_h264liveSMS * rtsp_h264liveSMS::createNew(UsageEnvironment & env,
                                               FramedSource * source,
                                               CRingBuffer<VidPacket> *ringbuffer)
{
	return new rtsp_h264liveSMS(env, source, ringbuffer);
}

FramedSource * rtsp_h264liveSMS::createNewStreamSource(unsigned clientSessionId, unsigned & estBitrate)
{
	return H264VideoStreamFramer::createNew(envir(), new rtsp_h264liveSrouce(envir(), m_ringBuffer));
}

RTPSink * rtsp_h264liveSMS::createNewRTPSink(Groupsock * rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource * inputSource)
{
	return H264VideoRTPSink::createNew(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic);
}

char const * rtsp_h264liveSMS::getAuxSDPLine(RTPSink * rtpSink, FramedSource * inputSource)
{
	if (m_pSDPLine)
	{
		return m_pSDPLine;
	}

	m_pDummyRTPSink = rtpSink;

	//mp_dummy_rtpsink->startPlaying(*source, afterPlayingDummy, this);
	m_pDummyRTPSink->startPlaying(*inputSource, 0, 0);

	chkForAuxSDPLine(this);

	m_done = 0;

	envir().taskScheduler().doEventLoop(&m_done);

	m_pSDPLine = strdup(m_pDummyRTPSink->auxSDPLine());

	m_pDummyRTPSink->stopPlaying();

	return m_pSDPLine;
}

void rtsp_h264liveSMS::afterPlayingDummy(void * ptr)
{
	rtsp_h264liveSMS * This = (rtsp_h264liveSMS *)ptr;

	This->m_done = 0xff;
}

void rtsp_h264liveSMS::chkForAuxSDPLine(void * ptr)
{
	rtsp_h264liveSMS * This = (rtsp_h264liveSMS *)ptr;

	This->chkForAuxSDPLine1();
}

void rtsp_h264liveSMS::chkForAuxSDPLine1()
{
	if (m_pDummyRTPSink->auxSDPLine())
	{
		m_done = 0xff;
	}
	else
	{
		double delay = 1000.0 / (FRAME_PER_SEC);  // ms
		int to_delay = delay * 1000;  // us

		nextTask() = envir().taskScheduler().scheduleDelayedTask(to_delay, chkForAuxSDPLine, this);
	}
}